package cn.qingyun.gis.modules.baogan.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.cache.common.facade.CacheFacade;
import cn.qingyun.gis.modules.baogan.entity.CrmStaff;
import cn.qingyun.gis.modules.baogan.service.CrmStaffService;
import cn.qingyun.gis.modules.baogan.vo.JingFenTeamData;
import cn.qingyun.gis.modules.baogan.mapper.CrmStaffMapper;
import cn.qingyun.gis.modules.express.util.SyncTool;
import cn.qingyun.gis.modules.init.system.entity.SftpConfig;
import cn.qingyun.gis.modules.init.utils.DictUtil;
import cn.qingyun.gis.modules.init.utils.SftpUtils;
import cn.qingyun.gis.modules.sftp.config.SftpProperties;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcraft.jsch.ChannelSftp;
import jodd.util.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 包干人员 团队 解析
 *
 * @author wanghui
 * @date 2024/11/5
 */
@RestController
@RequestMapping("/test/job")
@Slf4j
public class ResponsibilityUserAnalyzeJob {

    @Resource
    private CrmStaffService crmStaffService;
    @Resource
    private CrmStaffMapper crmStaffMapper;
    @Resource
    private SftpProperties config;

    private static final String STAFF_ROLE = "staffrole-resourceallocation-info_";
    private static final String STAFF_BASIC_INFO = "staffbasicinfo-channel-info_";
    private static final String JING_FEN_SPLITTER = "\\$\\#\\$";

    /**
     * 解析包干人员信息
     */
    @SneakyThrows
    public void analyzeUserInfo() {
        // 链接SFTP
        SftpConfig config = new SftpConfig();
        BeanUtil.copyProperties(this.config, config);
        ChannelSftp sftp = SftpUtils.createSftp(config);
        String filePath = "/home/gis1/baogan";
        String fileName1 = "staffbasicinfo-channel-info_20241106_001.csv";
        String fileName2 = "staffrole-resourceallocation-info_20241106_001.csv";
        String fileName3 = "WW071220241020000000.csv";
        String tempPath = "/tmp/bnaogan";
        File file1 = SftpUtils.downloadFile(filePath, fileName1, tempPath, sftp);
        File file2 = SftpUtils.downloadFile(filePath, fileName2, tempPath, sftp);
        File file3 = SftpUtils.downloadFile(filePath, fileName3, tempPath, sftp);
        log.debug("文件下载成功！！");
        log.debug("file1！！" + file1.length());
        log.debug("file2！！" + file2.length());
        log.debug("file3！！" + file3.length());


//        CsvTool.transferFile(file, ExpressRegion.class);
        //  数据处理
        // 入库

        file1.deleteOnExit();
        file2.deleteOnExit();
        file3.deleteOnExit();

    }

    @SneakyThrows
    /**
     * 解析团队信息
     */
    public void analyzeTeamInfo() {
        // 链接SFTP
        SftpConfig config = initJingFenConfig();
        BeanUtil.copyProperties(this.config, config);
        ChannelSftp sftp = SftpUtils.createSftp(config);
        String filePath = "/home/gis1/baogan";
//        String filePath = config.getFilePath();
//        String fileName = "WW071"+ DateUtil.format(DateUtil.yesterday(), "yyyyMMdd") + "000000.csv";
        String fileName = "WW071220241020000000.csv";
        String tempPath = "/tmp/bnaogan";
        File teamFile = SftpUtils.downloadFile(filePath, fileName, tempPath, sftp);
        log.debug("download success ！！teamFile size :" + teamFile.length());
        //  数据处理
        List<JingFenTeamData> teamDataList = parseTeamFile(teamFile);
        // TODO 入库

        teamFile.deleteOnExit();
    }

    @SneakyThrows
//    @GetMapping("/supple/info")
    /**
     * 补充CRM 人员信息
     */
    public void suppleCrmInfo() {
        int batchSize = 2000;
        QueryWrapper<CrmStaff> crmStaffQueryWrapper = new QueryWrapper<>();
        int count = crmStaffService.count(crmStaffQueryWrapper);
        int pages = (count / batchSize) + 1;
        // 获取能力开放平台访问token
        String accessToken = getAbilityAccessToken();
        if (StringUtil.isEmpty(accessToken)) {
            return;
        }
        SyncTool.doSync(pages, i -> {
            Page<CrmStaff> page = new Page<>(i, batchSize);
            Page<CrmStaff> crmStaffPage = crmStaffMapper.selectPage(page, crmStaffQueryWrapper);
            List<CrmStaff> crmStaffList = crmStaffPage.getRecords();
            for (CrmStaff crmStaff : crmStaffList) {

//                qryStaffBasicInfo(crmStaff, accessToken);
//                getGridInfoByAccount(crmStaff, accessToken);
//                qryRwdAreaInfo(crmStaff, accessToken);
                crmStaff.setId(IdUtil.simpleUUID());
            }
            crmStaffService.saveBatch(crmStaffList);
        });

    }

    /**
     * 获取能力开放平台访问token
     *
     * @return
     */
    private String getAbilityAccessToken() {

        String accessToken = (String) CacheFacade.get("sys:cache:temp:accessToken");
        if (ObjectUtil.isNotNull(accessToken)) {
            log.info("获取能力开放平台访问token结束 accessToken is not null");
            return accessToken;
        }
        String url = "http://192.195.66.12/openapi/restOauth2Server/access_token";
        String clientId = "20190221102192802";
        String clientSecret = "34f85ca80ec353d3052b8a2d3973a0c5";

        HttpRequest httpRequest = HttpRequest.post(url).form("grant_type", "client_credentials").form("client_id", clientId).form("client_secret", clientSecret);
        int status = httpRequest.execute().getStatus();
        if (status != 200) {
            log.info("获取能力开放平台访问token结束 请求失败");
            return null;
        }
        String result = httpRequest.execute().body();
        log.info("获取能力开放平台访问token结束 result:{}", result);
        JSONObject jsonResult = JSONUtil.parseObj(result);
        accessToken = jsonResult.getStr("access_token");
        if (ObjectUtil.isEmpty(accessToken)) {
            log.info("获取能力开放平台访问token结束 accessToken is empty");
            return null;
        }

        CacheFacade.set("sys:cache:temp:accessToken", accessToken, 604000);
        return accessToken;
    }

    private void qryStaffBasicInfo(CrmStaff crmStaff, String accessToken) {
        String requestUrl = "http://192.195.66.12/openapi/httpService/CommonService?method=QryStaffbasicInfo&access_token=" + accessToken;

        JSONObject request = new JSONObject();
        request.putOnce("STAFFID", crmStaff.getCrmAccount());
        request.putOnce("REGION", crmStaff.getRegion());

        HttpRequest httpRequest = HttpRequest.post(requestUrl).header(Header.CONTENT_TYPE, "application/json; charset=GBK").body(JSONUtil.toJsonStr(request));

        String responseBody = httpRequest.execute().body();
        log.info("qryStaffBasicInfo responseBody:{}", responseBody);
        JSONObject staffBasicInfoResponse = JSONUtil.parseObj(responseBody);
        String resCode = staffBasicInfoResponse.getStr("res_code");
        if ("0".equals(resCode)) {
            String result = staffBasicInfoResponse.getStr("result");
            JSONObject resultJO = JSONUtil.parseObj(result);
            String servnumber = resultJO.getStr("SERVNUMBER");
            String roleInfos = resultJO.getStr("ROLEINFOS");
            crmStaff.setPhone(servnumber);
            crmStaff.setRoleInfos(roleInfos);
        }

    }

    private void getGridInfoByAccount(CrmStaff crmStaff, String accessToken) {
        String requestUrl = "http://192.195.66.12/openapi/httpService/ISSSService?method=getGridInfoByAccount&access_token=" + accessToken + "&crmAccount=" + crmStaff.getCrmAccount();

        HttpRequest httpRequest = HttpRequest.get(requestUrl).header(Header.CONTENT_TYPE, "application/json; charset=GBK");

        String responseBody = httpRequest.execute().body();
        log.info("getGridInfoByAccount responseBody:{}", responseBody);
        JSONObject staffGridInfoResponse = JSONUtil.parseObj(responseBody);
        String resCode = staffGridInfoResponse.getStr("res_code");
        if ("0".equals(resCode)) {
            String result = staffGridInfoResponse.getStr("result");
            JSONObject resultJO = JSONUtil.parseObj(result);
            String gridCode = resultJO.getStr("gridCode");
            String gridName = resultJO.getStr("gridName");
            crmStaff.setGridCode(gridCode);
            crmStaff.setGridName(gridName);
        }
    }

    private void qryRwdAreaInfo(CrmStaff crmStaff, String accessToken) {
        String requestUrl = "http://192.195.66.12/openapi/httpService/ISSSService?method=qryRwdAreaInfo&access_token=" + accessToken;

        JSONObject request = new JSONObject();
        request.putOnce("REGION", crmStaff.getRegion());
        request.putOnce("OPERID", crmStaff.getCrmAccount());
        request.putOnce("AREAID", crmStaff.getChannelCode());

        HttpRequest httpRequest = HttpRequest.post(requestUrl).header(Header.CONTENT_TYPE, "application/json; charset=GBK").body(JSONUtil.toJsonStr(request));

        String responseBody = httpRequest.execute().body();
        log.info("qryRwdAreaInfo responseBody:{}", responseBody);
        JSONObject staffBasicInfoResponse = JSONUtil.parseObj(responseBody);
        String resCode = staffBasicInfoResponse.getStr("res_code");
    }


    @SneakyThrows
    private List<JingFenTeamData> parseTeamFile(File teamFile) {
        List<JingFenTeamData> teamDataList = new ArrayList<>();
        // 创建输入文件的Scanner对象
        Scanner scanner = new Scanner(teamFile);
        try {
            // 逐行读取CSV文件
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String replace = "\"" + line.replace("$" + "#" + "$", "\",\"") + "\"";
                // 使用split()方法将每行数据按照分隔符拆分成单列元素
                String[] columns = replace.split(",");
                if (columns.length >= 23) {
                    JingFenTeamData teamData = new JingFenTeamData();
                    teamData.setUserId(dealJingFenData(columns[0]));
                    teamData.setUserName(dealJingFenData(columns[1]));
                    teamData.setUserEmployeeNumber(dealJingFenData(columns[2]));
                    teamData.setUserPhone(dealJingFenData(columns[3]));
                    teamData.setOrgCode(dealJingFenData(columns[4]));
                    teamData.setOrgName(dealJingFenData(columns[5]));
                    teamData.setUserCityCode(dealJingFenData(columns[6]));
                    teamData.setUserCity(dealJingFenData(columns[7]));
                    teamData.setUserDistrictCode(dealJingFenData(columns[8]));
                    teamData.setUserDistrict(dealJingFenData(columns[9]));
                    teamData.setUserGrid(dealJingFenData(columns[10]));
                    teamData.setUserGridName(dealJingFenData(columns[11]));
                    teamData.setUserIdentity(dealJingFenData(columns[12]));
                    teamData.setUpdateDate(dealJingFenData(columns[13]));
                    teamData.setTeamId(dealJingFenData(columns[14]));
                    teamData.setTeamName(dealJingFenData(columns[15]));
                    teamData.setCreateDate(dealJingFenData(columns[16]));
                    teamData.setUserCaptainName(dealJingFenData(columns[17]));
                    teamData.setUserCaptainJob(dealJingFenData(columns[18]));
                    teamData.setUserCaptainPhone(dealJingFenData(columns[19]));
                    teamData.setOrgCaptainCode(dealJingFenData(columns[20]));
                    teamData.setOrgCaptainName(dealJingFenData(columns[21]));
                    teamData.setUpdateCaptainDate(dealJingFenData(columns[22]));
                    teamDataList.add(teamData);
                } else {
                    log.info("columns size < 23 columns[0] ：{}", columns[0]);
                }
            }
            // 关闭原文件
            log.debug("csv文件分隔符转换完成");
        } catch (Exception e) {
            log.error("Parse jingfen File error is :{}", e.getLocalizedMessage(), e);
            e.printStackTrace();
        } finally {
            scanner.close();
        }
        log.info("teamDataList size : {}", teamDataList.size());
        return teamDataList;
    }

    private String dealJingFenData(String data) {
        return data.replace("\"", "").trim();
    }

    private SftpConfig initCrmSftpConfig() {
        log.debug("ResponsibilityUserAnalyzeJob initSftpConfig begin");
        SftpConfig config = new SftpConfig();
        String crmStaffConfig = DictUtil.getDictItemValueByName(SftpUtils.SFTP_CONFIG, "BaoganCrmStaffInfoConfig");
        String desc = DictUtil.getDescValueByName(SftpUtils.SFTP_CONFIG, "BaoganCrmStaffInfoConfig");
        log.debug("ResponsibilityUserAnalyzeJob initCrmSftpConfig crmStaffConfig :{}", crmStaffConfig);
        String[] staffConfig = crmStaffConfig.split(":");
        if (staffConfig.length < 4) {
            log.debug("ResponsibilityUserAnalyzeJob initCrmSftpConfig end config error");
            return null;
        }
        // 查询字典配置   设置sftp 参数
        config.setHost(staffConfig[0]);
        config.setPort(Integer.parseInt(staffConfig[1]));
        config.setUsername(staffConfig[2]);
        config.setPassword(staffConfig[3]);
        config.setFilePath(desc);
        log.debug("ResponsibilityUserAnalyzeJob initCrmSftpConfig end");
        return config;
    }

    private SftpConfig initJingFenConfig() {
        log.debug("ResponsibilityUserAnalyzeJob initJingFenConfig begin");
        SftpConfig jingFenSftpConfig = new SftpConfig();
        String jingFenConfig = DictUtil.getDictItemValueByName(SftpUtils.SFTP_CONFIG, "BaoganJingFenConfig");
        String desc = DictUtil.getDescValueByName(SftpUtils.SFTP_CONFIG, "BaoganJingFenConfig");
        log.debug("ResponsibilityUserAnalyzeJob initJingFenConfig jingFenConfig :{}", jingFenConfig);
        String[] jingFenConfigArr = jingFenConfig.split(":");
        if (jingFenConfigArr.length < 4) {
            log.debug("ResponsibilityUserAnalyzeJob initJingFenConfig end config error");
            return null;
        }
        // 查询字典配置   设置sftp 参数
        jingFenSftpConfig.setHost(jingFenConfigArr[0]);
        jingFenSftpConfig.setPort(Integer.parseInt(jingFenConfigArr[1]));
        jingFenSftpConfig.setUsername(jingFenConfigArr[2]);
        jingFenSftpConfig.setPassword(jingFenConfigArr[3]);
        jingFenSftpConfig.setFilePath(desc);
        log.debug("ResponsibilityUserAnalyzeJob initJingFenConfig end");
        return jingFenSftpConfig;
    }
}
